package com.ruoyi.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dyun.tool.mybatis.domain.BaseEntity;
import com.dyun.tool.mybatis.domain.PageDomain;
import com.ruoyi.project.setting.security.utils.UserUtils;
import com.ruoyi.project.setting.utils.DataScopeUtils;
import com.ruoyi.common.annotation.SysLog;
import com.ruoyi.common.constant.CommonConstants;
import com.ruoyi.common.enums.BusinessTypeEnum;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.support.DateRange;
import com.ruoyi.project.system.entity.SysDept;
import com.ruoyi.project.system.entity.SysRole;
import com.ruoyi.project.system.service.ISysDeptService;
import com.ruoyi.project.system.service.ISysRoleService;
import com.ruoyi.project.system.vo.SysRoleMenuVO;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import net.dreamlu.mica.core.result.R;
import net.dreamlu.mica.core.utils.$;
import net.dreamlu.mica.core.validation.CreateGroup;
import net.dreamlu.mica.core.validation.UpdateGroup;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色 控制层
 *
 * @author dy
 */
@RestController
@RequestMapping("/system/role")
@AllArgsConstructor
public class SysRoleController extends BaseController {

    private final ISysRoleService sysRoleService;

    private final ISysDeptService sysDeptService;

    /**
     * 列表
     */
    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @GetMapping("/list")
    public R list(SysRole sysRole, PageDomain pageDomain, DateRange dateRange) {
        // 根据父ID查询所有子ID
        List<SysDept> sysDepts = new ArrayList<>();
        if ($.isNotNull(sysRole.getCreateDept())) {
            sysDepts = sysDeptService.list(new LambdaQueryWrapper<SysDept>()
                    .eq(SysDept::getId, sysRole.getCreateDept())
                    .or()
                    .apply(CommonConstants.SQL_FIND_IN_SET, sysRole.getCreateDept()));
        }
        LambdaQueryWrapper<SysRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .like($.isNotBlank(sysRole.getRoleName()), SysRole::getRoleName, sysRole.getRoleName())
                .eq($.isNotNull(sysRole.getStatus()), SysRole::getStatus, sysRole.getStatus())
                .like($.isNotBlank(sysRole.getRoleKey()), SysRole::getRoleKey, sysRole.getRoleKey())
                .in($.isNotEmpty(sysDepts), SysRole::getCreateDept, sysDepts.stream().map(BaseEntity::getId).collect(Collectors.toList()))
                .between($.isAnyNotBlank(dateRange.getBeginTime(), dateRange.getEndTime()), SysRole::getCreateTime, dateRange.getBeginTime(), dateRange.getEndTime())
                .apply(DataScopeUtils.getDataScopeSql("sys_role"), 1);
        if ($.isNull(pageDomain.getPageNum())) {
            List<SysRole> list = sysRoleService.list(queryWrapper);
            return success(list);
        } else {
            IPage<SysRole> pages = sysRoleService.page(startPage(pageDomain), queryWrapper);
            return success(pages);
        }
    }

    /**
     * 详情
     */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping("/detail")
    public R<SysRole> detail(Long id) {
        SysRole sysRole = sysRoleService.getById(id);
        return success(sysRole);
    }

    /**
     * 新增
     */
    @SysLog(title = "角色管理", businessType = BusinessTypeEnum.INSERT)
    @PreAuthorize("@ss.hasPermi('system:role:add')")
    @PostMapping("/add")
    public R add(@Validated(value = {CreateGroup.class}) @RequestBody SysRoleMenuVO sysRoleMenuVO) {
        SysRole roleCheck = sysRoleService.getOne(new LambdaQueryWrapper<SysRole>().eq(SysRole::getRoleKey, sysRoleMenuVO.getRoleKey()));
        if ($.isNotNull(roleCheck)) {
            return fail("新增角色'" + sysRoleMenuVO.getRoleName() + "'失败，无法修改为该权限");
        }
        return status(sysRoleService.addRoleMenu(sysRoleMenuVO));
    }

    /**
     * 修改
     */
    @SysLog(title = "角色管理", businessType = BusinessTypeEnum.UPDATE)
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @PutMapping("/update")
    public R update(@Validated(value = {UpdateGroup.class}) @RequestBody SysRoleMenuVO sysRoleMenuVO) {
        if (UserUtils.isAdmin(sysRoleMenuVO.getId())) {
            return fail("不允许操作超级管理员角色");
        }
        SysRole roleCheck = sysRoleService.getOne(new LambdaQueryWrapper<SysRole>().eq(SysRole::getRoleKey, sysRoleMenuVO.getRoleKey()));
        if ($.isNotNull(roleCheck) && !roleCheck.getId().equals(sysRoleMenuVO.getId())) {
            return fail("修改角色'" + sysRoleMenuVO.getRoleName() + "'失败，无法修改为该权限");
        }
        return status(sysRoleService.updateRoleMenu(sysRoleMenuVO));
    }

    /**
     * 修改角色信息
     */
    @SysLog(title = "角色管理", businessType = BusinessTypeEnum.UPDATE)
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @PutMapping("/partialupdate")
    public R partialupdate(@Validated(value = {UpdateGroup.class}) @RequestBody SysRole sysRole) {
        if (UserUtils.isAdmin(sysRole.getId())) {
            return fail("不允许操作超级管理员角色");
        }
        SysRole updateRole = new SysRole();
        updateRole.setId(sysRole.getId());
        updateRole.setStatus(sysRole.getStatus());
        Integer dataScope = sysRole.getDataScope();
        if ($.isNotNull(dataScope)) {
            if (!DataScopeUtils.checkRange(dataScope)) {
                return fail("无效的数据权限范围");
            }
            updateRole.setDataScope(sysRole.getDataScope());
        }
        return status(sysRoleService.updateById(updateRole));
    }

    /**
     * 删除
     */
    @SysLog(title = "角色管理", businessType = BusinessTypeEnum.DELETE)
    @PreAuthorize("@ss.hasPermi('system:role:remove')")
    @DeleteMapping("/delete/{ids}")
    @SneakyThrows
    public R delete(@PathVariable Long[] ids) {
        List<SysRole> sysRoles = new ArrayList<>();
        List<Long> idList = new ArrayList<>(Arrays.asList(ids));
        idList.forEach(v -> {
            if (v.equals(1L)) {
                throw new CustomException("不允许操作超级管理员角色");
            }
            SysRole sysRole = new SysRole();
            sysRole.setId(v);
            sysRoles.add(sysRole);
        });
        boolean result = sysRoleService.updateBatchById(sysRoles) && sysRoleService.removeByIds(idList);
        return status(result);
    }
}
